package main;

import java.util.concurrent.atomic.AtomicInteger;

public class CandySamplerThread extends Thread
{
	private int nibbleCount;
	private final int threadID;
	private final CandyBox box;
	private boolean finished = false;
	private static final AtomicInteger uniqueID =
		new AtomicInteger(1);
	
	public CandySamplerThread( CandyBox box )
	{
		this.threadID = uniqueID.getAndIncrement();
		this.box = box;
		this.nibbleCount = 0;
	}
	
	public void run()
	{
		Candy candy = new Candy();
		while( !Thread.interrupted() && !finished )
		{
			try
			{
				// operations on an individual candy 
				// can only be invoked by one thread
				// at a time, hence they are not synchronized
				candy = box.sampleCandy(this);
				if( !candy.isNibbledByCurrThread() )
				{
					// we haven't tried this one before
					candy.nibble();
					System.out.println( toString() + " nibbled " + 
							candy.toString() + " and says, \"meh\"");
					++nibbleCount;
				}
				else
				{
					System.out.println( toString() + " noticed its tooth " +
							"marks on " + candy.toString() + " and says, " +
									"\"already tried that one\".");
				}
				// return the candy, sleep
				box.returnCandy(this, candy);
				candy = null;
				Thread.sleep(100);
				if( nibbleCount == box.getCapacity() )
				{
					System.out.println( toString() + " says, \"Phooey. I've " +
							"tried everything!\"");
					finished = true;
				}
			} 
			catch ( InterruptedException e )
			{
				if(candy != null)
				{
					box.returnCandy(this, candy); // return the candy if we have one
				}
				Thread.currentThread().interrupt();
			}
		}
	}
	
	public void printStatus()
	{
		String s = toString();
		if( finished || (nibbleCount == box.getCapacity()) )
		{
			s = s + " sampled every candy! :)";
		}
		else {
			s = s + " only sampled " + nibbleCount + " candies. :(";
		}
		System.out.println(s);
	}
	
	public int getThreadID()
	{
		return this.threadID;
	}
	
	public String toString()
	{
		return "Thread #" + getThreadID();
	}
}
